package com.zyx.concurrentdemo.c06cas;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author Yaxi.Zhang
 * @since 2021/10/18 14:06
 * desc: Unsafe案例
 * Unsafe并不是指该类线程不安全, 而是指操作贴近底层, 使用时容易不安全
 */
public class TestUnsafe {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        // 反射获取Unsafe对象
        Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
        // 私有属性
        unsafeField.setAccessible(true);
        // 静态属性的获取
        Unsafe unsafe = (Unsafe)unsafeField.get(null);

        // 1. 获取域的偏移地址
        long iOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("id"));
        long nOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("id"));

        // 2. 执行 cas 操作
        Teacher teacher = new Teacher();
        unsafe.compareAndSwapInt(teacher, iOffset, 0, 1001);
        unsafe.compareAndSwapObject(teacher, nOffset, null, "张三");

        // 3. 验证
        System.out.println(teacher);
    }
}

class Teacher {
    private volatile int id;
    private volatile String name;

    @Override
    public String toString() {
        return "Teacher{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
